package com.team.ai.service;

import com.team.ai.tool.Baidu.Current.FileUtil;
import com.team.ai.tool.Baidu.Current.GsonUtils;
import com.team.ai.tool.Baidu.Current.HttpUtil;
import com.team.ai.tool.Baidu.Current.OCRAuthService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 人脸属性编辑
 */
@Component
public class EditattrService {
    @Resource
    OCRAuthService ocrAuthService;//OCR令牌
    public  String faceMerge(String filePath,String actionType,String target) {
        byte[] bytes = new byte[0];
        try {
            bytes = FileUtil.readFileByBytes(filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String encodeValue = Base64Utils.encodeToString(bytes);

        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v1/editattr";
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("image", encodeValue);
            map.put("image_type", "BASE64");
            map.put("action_type",actionType);
            if ("V2_AGE".equals(actionType) || "V2_GENDER".equals(actionType)){
                map.put("target",target);
            }

            String param = GsonUtils.toJson(map);

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = ocrAuthService.getAuth(18);;

            String result = HttpUtil.post(url, accessToken, "application/json", param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
